package com.example.flutterappmydemo;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity implements EventChannel.StreamHandler {

    private static final String USERINFOEDITCHANNEL = "flutter_plugin_demo_java";
    private EventChannel.EventSink eventSink;


    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        System.out.println("MainActivityypk.configureFlutterEngine");


        MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), USERINFOEDITCHANNEL);
        methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {

                if (call.method.equals("showToast")) {
                    String text = call.argument("text");
                    showToast(text);
                    result.success("success");
                } else if (call.method.equals("openActivity")) {
                    openActivity();
                    result.success("success");
                } else {
                    result.notImplemented();
                }

            }
        });

        EventChannel mEventChannel = new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "flutter_plugin_demo_java1");
        mEventChannel.setStreamHandler(this);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("MainActivityypk.onCreate");

    }

    private void showToast(String text) {
        if (eventSink != null) {
            Map<String, Object> map = new HashMap();
            map.put("userid", "11");
            map.put("age", 18);
            eventSink.success(map);
        } else {
            System.out.println("MainActivity.onCreate eventSink is null");
        }
        Toast.makeText(this, "java-" + text, Toast.LENGTH_SHORT).show();
    }

    private void openActivity() {
        startActivity(new Intent(this, SecondActivity.class));
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink eventSink) {
        System.out.println("MainActivity.onListen");
        if (eventSink != null) {
            this.eventSink = eventSink;
        }
    }

    @Override
    public void onCancel(Object arguments) {
        System.out.println("MainActivity.onCancel");
    }
}
